package com.yl.androidutilscenter.base

import android.app.Application
import androidx.appcompat.app.AppCompatActivity
import com.orhanobut.logger.AndroidLogAdapter
import com.orhanobut.logger.Logger
import com.tencent.mmkv.MMKV
import com.yl.androidutilscenter.utils.LogUtils

/**
 * @author
 * @description: Application基类
 * @date :2024/3/8
 * @version 1.0.0
 */
abstract class BaseApplication : Application() {

    private val allActivity by lazy { mutableListOf<AppCompatActivity>() }

    companion object {
        private lateinit var INSTANCE: BaseApplication
        fun getInstance(): BaseApplication {
            return INSTANCE
        }
    }


    override fun onCreate() {
        super.onCreate()
        INSTANCE = this
        MMKV.initialize(this)
        LogUtils.initLog(initLogTagName())
        init()
    }


    open fun initLogTagName(): String {
        return "AndroidCenterLog"
    }

    /**
     * 应用终止是调用
     */
    override fun onTerminate() {
        super.onTerminate()
        allActivity.clear()
    }

    fun addActivityToList(activity: AppCompatActivity) {
        allActivity.add(activity)
    }

    fun removeActivityFromList(activity: AppCompatActivity) {
        if (allActivity.contains(activity)) {
            allActivity.remove(activity)
        }
    }

    /**
     * 获取当前顶部activity
     *
     * @return
     */
    fun getTopActivity(): AppCompatActivity? {
        return if (allActivity.size > 0) {
            allActivity[allActivity.size - 1]
        } else {
            null
        }
    }

    /**
     * 关闭所有Activity
     */
    fun finishAll() {
        for (a in allActivity) {
            a.finish()
        }
    }


    /**
     * 初始化事件
     */
    abstract fun init()

}